import React, { useReducer } from "react";
import { Divider } from "antd";
import Message from "../../componments/Message";
import Navbar from "../../componments/Navbar";
import Counter from "../../componments/Counter";
import { connect } from "react-redux";

const reducer = (state: any, action: any) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
};
const initialState = { count: 0 };

export const AppContext = React.createContext<any>({ username: "" });

const ReduxSagaDemo = (props: any) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      <h1>Hooks useReducer使用</h1>
      <AppContext.Provider
        value={{
          username: "superawesome",
        }}
      >
        Count: {state.count}
        <button onClick={() => dispatch({ type: "decrement" })}>-</button>
        <button onClick={() => dispatch({ type: "increment" })}>+</button>
        <Message />
        <Navbar />
      </AppContext.Provider>

      <Divider />

      <h1>Redux-saga 使用</h1>
      <Counter
        value={props.count}
        onIncrement={() => props.incrementCount()}
        onDecrement={() => props.decrementCount()}
        onIncrementAsync={() => props.incrementCountAsync()}
      />
    </>
  );
};

const mapStateToProps = (state: any) => {
  return {
    posts: state.shoppingCart.posts,
    cart: state.shoppingCart.cart,
    count: state.counts.count
  };
};

const mapDispatchToProps = (dispatch: any) => {
  return {
    incrementCount: () => dispatch({type: 'INCREMENT'}),
    decrementCount: () => dispatch({type: 'DECREMENT'}),
    incrementCountAsync: () => dispatch({type: 'INCREMENT_ASYNC'}),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(ReduxSagaDemo);
